<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'
import { ref } from 'vue'

const rules = ref([
  {
    id: 1,
    type: '实时',
    ruleName: '宕机',
    metric: 'up',
    description: '主机宕机',
    expression: 'up',
    comparison: '==',
    threshold: 0,
    severity: 99,
    updateTime: '2024-04-29 22:25:31'
  }
])

//分页条数据模型
const page = ref(1)//当前页
const total = ref(20)//总条数
const pageSize = ref(8)//每页条数

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  pageSize.value = size
  alertRuleList()
}
//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  page.value = num
  alertRuleList()
}

//弹窗复用问题解决
//控制弹窗
const dialogVisible = ref(false)

//控制编辑模式
const isEditMode = ref(false);
//定义变量控制标题的展示
const dialogTitle = ref('')
//添加规则数据模型
const alertRuleModel = ref({
  type: '',
  ruleName: '',
  metric: '',
  description: '',
  expression: '',
  comparison: '',
  threshold: '',
  severity: ''
})

//添加分类表单校验
const formRules = {
  type: [
    { required: true, message: '请输入类型', trigger: 'change' }
  ],
  ruleName: [
    { required: true, message: '请输入规则名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  metric: [
    { required: true, message: '请输入指标', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入描述', trigger: 'blur' }
  ],
  expression: [
    { required: true, message: '请输入表达式', trigger: 'blur' }
  ],
  comparison: [
    { required: true, message: '请输入比较', trigger: 'change' }
  ],
  threshold: [
    { required: true, message: '请输入阈值', trigger: 'blur' },
  ],
  severity: [
    { required: true, message: '请输入告警级别', trigger: 'blur' },
  ]
};
// 定义改变类型时的处理函数
const handleTypeChange = () => {
  console.log(alertRuleModel.type);
  if (!alertRuleModel.type) {
    callback(new Error('请选择规则类型'));
  } else {
    callback();
  }
};



import { articleRuleListService, addAlertRuleService, alertRuleDeleteService, alertRuleUpdateService } from '@/api/rules.js'


//查询规则
const alertRuleList = async () => {
  let params = {
    page: page.value,
    pageSize: pageSize.value,
  }
  let result = await articleRuleListService(params);

  //渲染视图
  total.value = result.data.data.total;
  rules.value = result.data.data.records;
}
alertRuleList();


// 将 "HH:mm:ss" 的时间格式转换为毫秒
function convertToMilliseconds(timeString) {
  const [hours, minutes, seconds] = timeString.split(':').map(Number);
  const milliseconds = (hours * 3600 + minutes * 60 + seconds) * 1000;
  return milliseconds;
}

//调用接口添加规则
const addAlertRule = async () => {

  //调用接口
  let result = await addAlertRuleService(alertRuleModel.value);

  if (result.status === 200) {
    ElMessage.success(result.msg ? result.msg : "添加成功！");
    //调用获取全部规则函数——刷新页面
    alertRuleList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(result.msg ? result.msg : "添加失败！");
  }
}

//不改变tyoe值的前提，展示实时计算
function renderRuleType(type) {
  return type === 0 ? '实时计算' : '定时计算';
}


//展示弹窗
const showDialog = (row = null) => {
  if (row) {
    // 编辑模式
    isEditMode.value = true;
    dialogTitle.value = '编辑规则';
    alertRuleModel.value = { ...row }; // 复制行数据
  } else {
    // 添加模式
    isEditMode.value = false;
    clearData(); // 清空模型数据
  }
  dialogVisible.value = true;
};

const onConfirm = () => {
  if (isEditMode.value) {
    updateAlertRule();
  } else {
    addAlertRule();
  }
};

//编辑分类
const updateAlertRule = async () => {



  let result = await alertRuleUpdateService(alertRuleModel.value)
  console.log(result);
  if (result.status === 200) {
    ElMessage.success(result.msg ? result.msg : "更新成功！");
    //调用获取全部规则函数——刷新页面
    alertRuleList();
    dialogVisible.value = false;
  } else {
    ElMessage.error(result.msg ? result.msg : "更新失败！");
  }
}

//清空模型数据
const clearData = () => {
  alertRuleModel.value.type = '';
  alertRuleModel.value.ruleName = '';
  alertRuleModel.value.metric = '';
  alertRuleModel.value.description = '';
  alertRuleModel.value.expression = '';
  alertRuleModel.value.comparison = '';
  alertRuleModel.value.threshold = '';
  alertRuleModel.value.severity = '';

}
import { ElMessage, ElMessageBox } from 'element-plus';
//删除弹窗
const deleteAlertRule = (row) => {
  ElMessageBox.confirm(
      '你确定删除该规则信息吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        //调用接口
        let result = await alertRuleDeleteService(row.id);
        ElMessage({
          type: 'success',
          message: '删除成功',
        });
        //调用获取全部文章函数——刷新页面
        alertRuleList();
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}

</script>

<template>
    <el-card class="page-container">
        <template #header>
            <div class="header">
                <span>告警规则列表</span>
                <div class="extra">
                    <el-button type="primary" @click="dialogVisible = true; dialogTitle = '添加规则';
                    isEditMode = false; clearData()">添加规则</el-button>
                </div>
            </div>
        </template>
        <el-table :data="rules" style="width: 100%" align-center>
            <el-table-column label="序号" type="index"></el-table-column>
            <el-table-column label="规则类型">
                <template #default="{ row }">
                    {{ renderRuleType(row.type) }}
                </template>
            </el-table-column>
            <el-table-column label="规则名称" prop="ruleName"></el-table-column>
            <el-table-column label="指标" prop="metric"></el-table-column>
            <el-table-column label="描述" prop="description"></el-table-column>
            <el-table-column label="规则计算表达式" prop="expression"></el-table-column>
            <el-table-column label="比较运算符" prop="comparison"></el-table-column>
            <el-table-column label="阈值" prop="threshold"></el-table-column>
            <el-table-column label="告警级别" prop="severity"></el-table-column>
            <el-table-column label="时间" prop="updateTime"></el-table-column>
            <el-table-column label="操作" width="100">
                <template #default="{ row }">
                    <el-button :icon="Edit" circle plain type="primary" @click="showDialog(row)"></el-button>
                    <el-button :icon="Delete" circle plain type="danger" @click="deleteAlertRule(row)"></el-button>
                </template>
            </el-table-column>
            <template #empty>
                <el-empty description="没有数据" />
            </template>
        </el-table>
        <!-- 分页条 -->
        <el-pagination v-model:current-page="page" v-model:page-size="pageSize" :page-sizes="[3, 5, 10, 15]"
            layout="jumper, total, sizes, prev, pager, next" background :total="total" @size-change="onSizeChange"
            @current-change="onCurrentChange" style="margin-top: 20px; justify-content: flex-end" />

        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="30%">
            <el-form :model="alertRuleModel" :rules="formRules" label-width="100px" style="padding-right: 30px">
                <!-- 根据情景条件动态渲染表单项 -->
                <template v-if="isEditMode">
                    <!-- 编辑模式下显示的表单项 -->
                    <el-form-item label="描述" prop="description">
                        <el-input v-model="alertRuleModel.description"></el-input>
                    </el-form-item>
                </template>
                <template v-else>
                    <!-- 添加模式下显示的表单项 -->
                    <el-form-item label="类型" prop="type">
                        <el-select v-model="alertRuleModel.type" @change="handleTypeChange" placeholder="请选择规则类型">
                            <el-option label="实时计算" value="0"></el-option>
                            <el-option label="定时计算" value="1"></el-option>
                            <!-- 其他比较运算符选项 -->
                        </el-select>
                    </el-form-item>
                    <el-form-item label="规则名称" prop="ruleName">
                        <el-input v-model="alertRuleModel.ruleName"></el-input>
                    </el-form-item>
                    <el-form-item label="指标" prop="metric">
                        <el-input v-model="alertRuleModel.metric"></el-input>
                    </el-form-item>
                    <el-form-item label="描述" prop="description">
                        <el-input v-model="alertRuleModel.description"></el-input>
                    </el-form-item>
                    <el-form-item label="表达式" prop="expression">
                        <el-input v-model="alertRuleModel.expression"></el-input>
                    </el-form-item>
                    <el-form-item label="比较" prop="comparison">
                        <el-select v-model="alertRuleModel.comparison" placeholder="请选择比较运算符">
                            <el-option label="==" value="=="></el-option>
                            <el-option label="!=" value="!="></el-option>
                            <el-option label=">" value=">"></el-option>
                            <el-option label="<" value="<"></el-option>
                            <el-option label="<=" value="<="></el-option>
                            <el-option label=">=" value=">="></el-option>
                        </el-select>
                    </el-form-item>
                </template>
                <!-- 共享的表单项 -->
                <el-form-item label="阈值" prop="threshold">
                    <el-input v-model="alertRuleModel.threshold" type="number"></el-input>
                </el-form-item>
                <el-form-item label="告警级别" prop="severity">
                    <el-input v-model="alertRuleModel.severity" type="number"></el-input>
                </el-form-item>
            </el-form>
            <!-- 弹窗底部按钮 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="onConfirm">确认</el-button>
                </span>
            </template>
        </el-dialog>

    </el-card>
</template>

<style lang="scss" scoped>
.page-container {
    min-height: 100%;
    box-sizing: border-box;

    .header {
        display: flex;
        align-items: center;
        justify-content: space-between;
    }

    .el-table .cell {
        text-align: center !important;
    }
}
</style>